﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace 自动分享工具
{
    public partial class Form1 : Form
    {
        List<string> baiduUserList = new List<string>();
        List<string> baiduPasswordList = new List<string>();
        List<string> baiduCommentList = new List<string>();
        Dictionary<string, string> shareDict = new Dictionary<string, string>();
        string BaiduThirdUrl = null;
        int baiduUserCount = 0;
        bool isLogged = false;
        bool isPosted = false;
        bool isInterrupt = false;
        string baiduLoginUrl = "https://passport.baidu.com/?login";

        public Form1()
        {
            InitializeComponent();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //webBrowser1.Navigate(toolStripTextBox1.Text.ToString());
            richTextBox1.Clear();
            richTextBox1.Enabled = false;

            shareDict = new Dictionary<string, string>();   //清空链接存储字典

            label1.Text = "首页中的下载链接";
            WebPage destPage = new WebPage(toolStripTextBox1.Text.ToString());
            string pattern = "http://down.ipagame.net/detail";
            int linkCount = Int16.MaxValue;
            List<Link> downLinks = destPage.getSpecialLinksByUrl(pattern, linkCount);
            List<string> links = new List<string>();
            downLinks.ForEach(delegate(Link link)
            {
                links.Add(link.url);
            });
            for (int i = links.Count - 1; i >= 0; --i)
            {
                if (links.IndexOf(links[i]) != i)
                    links.RemoveAt(i);
            }
            links.Sort();

            int count = 1;
            links.ForEach(delegate(string link)
                {
                    if (link != null)
                    {
                        //Console.WriteLine(string.Format("{0}+++{1}",link.url,link.text));
                        WebPage newPage = new WebPage(link);
                        if (newPage.Title != "")
                        {
                            shareDict.Add(link, newPage.Title);

                            richTextBox1.AppendText(string.Format("{0} \t{1}\n", link.ToString(), shareDict[link]));
                            this.richTextBox1.Focus();                                  //让文本框获取焦点
                            this.richTextBox1.Select(this.richTextBox1.TextLength, 0);  //设置光标的位置到文本尾
                            this.richTextBox1.ScrollToCaret();                          //滚动到控件光标处
                            label1.Text = "页面中的链接个数为:" + count;
                            count++;
                        }
                    }
                    Application.DoEvents();
                });
            label1.Text += " \t分析链接完毕";
            richTextBox1.Enabled = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripTextBox1.Enabled = false;
            toolStripTextBox1.Text = "http://www.ipagame.net";

            toolStripButton1.Enabled = false;
            toolStripButton2.Enabled = false;
            toolStripButton4.Enabled = false;
            toolStripButton5.Enabled = false;

            textBox3.Text = "http://www.ipagame.net";
        }

        /*
        private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            label2.Text = e.LinkText + "网页内容";
            WebPage destPage = new WebPage(e.LinkText);
            richTextBox2.AppendText("打开了 " + destPage.URL + "\n");
            string sohuUrl = "http://t.sohu.com/third/post.jsp?url=" + destPage.URL + "&title=" + destPage.Title + "&content=gb2312";
            destPage = new WebPage(sohuUrl, "gb2312");
            richTextBox2.AppendText("打开了 " + destPage.URL + "\n");
            //string sohuLoginUrl = "http://passport.sohu.com";
            //destPage = new WebPage(sohuLoginUrl);

            //string sohuUserName = userList[1];
            //string sohuPassword = passwordList[1];
            //string sohuPostData = string.Format("http://passport.sohu.com/sso/login.jsp?userid={0}&password={1}&appid=9998&persistentcookie=0&isSLogin=1&s=1308584053421&b=2&w=1600&pwdtype=1&v=26", sohuUserName, sohuPassword);

            //destPage = new WebPage(destPage.URL, sohuLoginUrl, sohuPostData);  //登录搜狐

            //webBrowser1.DocumentText = destPage.HtmlContext;
            label2.Text = destPage.Title + " 中的网页内容";

            string contextPage = destPage.HtmlContext;
            webBrowser1.Navigate(e.LinkText);
            webBrowser1.Navigate("http://t.sohu.com/third/post.jsp?url=" + e.LinkText + "&title="+webBrowser1.DocumentTitle + "&content=gb2312");
        }
        */

        private void Form1_Resize(object sender, EventArgs e)
        {
            richTextBox1.Size = new System.Drawing.Size(panel1.Width - 24, 120);
            richTextBox2.Size = new System.Drawing.Size(panel1.Width - 24, 120);
            webBrowser1.Size = new System.Drawing.Size(panel1.Width - 24, panel1.Height - richTextBox1.Height - label1.Height - label2.Height - 24);
        }

        private string getMd5Hash(string input)
        {
            MD5 md5Hasher = MD5.Create();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            return sBuilder.ToString();
        }


        private void webBrowser1_Login_Baidu(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if ((baiduUserCount) >= baiduUserList.Count)
            {
                baiduUserCount = 0; //用户从头再来
            }

            if (loginBaidu(baiduUserList[baiduUserCount], baiduPasswordList[baiduUserCount]))
            {

                webBrowser1.DocumentCompleted -= (webBrowser1_Login_Baidu);
                webBrowser1.DocumentCompleted += (webBrowser1_Post_Baidu);
                webBrowser1.Navigate(BaiduThirdUrl);
                Application.DoEvents();
                baiduUserCount++;
            }
            Application.DoEvents();
        }


        /// <summary>
        /// 读取用户和密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            string sohuUserName = baiduUserList[1];
            string sohuPassword = baiduPasswordList[1];
            string sohuPostData = string.Format("http://passport.sohu.com/sso/login.jsp?userid={0}&password={1}&appid=9998&persistentcookie=0&isSLogin=1&s=1308584053421&b=2&w=1600&pwdtype=1&v=26", sohuUserName, sohuPassword);
            WebPage destPage = new WebPage("http://t.sohu.com");
            destPage = new WebPage("http://t.sohu.com", "http://passport.sohu.com", sohuPostData);
            richTextBox2.AppendText(destPage.Host + "\t" + destPage.Title + "\t" + destPage.URL + "\n" + destPage.HtmlContext + "\n");
        }

        private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            if (shareDict.ContainsKey(e.LinkText))
            {
                BaiduThirdUrl = string.Format("http://share.baidu.com/s?url={0}&to=tieba&type=text&relateUid=&pic=&title={1}", e.LinkText, shareDict[e.LinkText]);
                removeIECookies();
                Application.DoEvents();
                System.Threading.Thread.Sleep(1000);

                webBrowser1.Navigate(baiduLoginUrl);
                webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_Login_Baidu);
            }
            Application.DoEvents();
        }

        private void webBrowser1_Post_Baidu(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.Url.ToString().IndexOf("/i/app/open_share_api") > 0)
            {
                //可以提交表单了
                //webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(webBrowser1_Post_Baidu);
                webBrowser1.DocumentCompleted -= webBrowser1_Post_Baidu;
                postBaiduTieba("这个游戏不错，很給力!");
                Application.DoEvents();
                System.Threading.Thread.Sleep(1000);

                removeIECookies();
                Application.DoEvents();
                System.Threading.Thread.Sleep(3000);

                webBrowser1.Navigate(baiduLoginUrl);
                //webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_Login_Baidu);
                webBrowser1.DocumentCompleted += webBrowser1_Login_Baidu;
            }
            Application.DoEvents();
        }

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            richTextBox2.AppendText(DateTime.Now + "\n" + e.Url.ToString() + "\n");
            this.richTextBox2.Focus();                                          //让文本框获取焦点
            this.richTextBox2.Select(this.richTextBox2.TextLength, 0);          //设置光标的位置到文本尾
            this.richTextBox2.ScrollToCaret();                                  //滚动到控件光标处
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            removeIECookies();
            Application.DoEvents();
            webBrowser1.Navigate(baiduLoginUrl);
        }

        /// <summary>
        /// 打开百度用户中心
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(baiduLoginUrl);
        }

        /// <summary>
        /// 登录百度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            //webBrowser1.Navigate("about:blank");
            //clearBrowserSession();
            richTextBox2.Clear();

            webBrowser1.Navigate(baiduLoginUrl);
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_Login_Baidu);

        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            foreach (KeyValuePair<string, string> kvp in shareDict)
            {
                BaiduThirdUrl = string.Format("http://share.baidu.com/s?url={0}&to=tieba&type=text&relateUid=&pic=&title={1}", kvp.Key, kvp.Value);
                removeIECookies();
                Application.DoEvents();
                System.Threading.Thread.Sleep(1000);

                webBrowser1.Navigate(baiduLoginUrl);
                //webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_Login_Baidu);
                webBrowser1.DocumentCompleted += (webBrowser1_Login_Baidu);
                Application.DoEvents();
                //System.Threading.Thread.Sleep(10000);

                while (!isPosted)
                {
                    if (isInterrupt)
                    {
                        isInterrupt = false;
                        return;
                    }
                    Application.DoEvents();
                }
                isPosted = false;

                if (isInterrupt)
                {
                    isInterrupt = false;
                    return;
                }

            }
            Application.DoEvents();

        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            isInterrupt = true;
            Application.DoEvents();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            foreach (KeyValuePair<string, string> kvp in shareDict)
            {
                BaiduThirdUrl = string.Format("http://share.baidu.com/s?url={0}&to=tieba&type=text&relateUid=&pic=&title={1}", kvp.Key, kvp.Value);
                removeIECookies();
                Application.DoEvents();
                System.Threading.Thread.Sleep(1000);
                webBrowser1.ScriptErrorsSuppressed = true;
                isLogged = false;
                isPosted = false;

                webBrowser1.Navigate(baiduLoginUrl);
                //webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);

                while (!isPosted)
                {
                    if (isInterrupt)
                    {
                        isInterrupt = false;
                        return;
                    }
                    Application.DoEvents();
                }
                //isPosted = false;

                baiduUserCount++;
                if (baiduUserCount >= baiduUserList.Count)
                {
                    baiduUserCount = 0;
                }

                if (isInterrupt)
                {
                    isInterrupt = false;
                    return;
                }

            }
            Application.DoEvents();

        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url == webBrowser1.Document.Url)
            {
                if (e.Url.LocalPath == "/" && !isLogged)
                {
                    Debug.WriteLine("\n未登录\n" + "这是e.Url:" + e.Url + "\n这是webBrowser1.Document.Url:" + webBrowser1.Document.Url);
                    loginBaidu(baiduUserList[baiduUserCount], baiduPasswordList[baiduUserCount]);
                    isLogged = true;
                }
                else if (e.Url.LocalPath == "/center")
                {
                    Debug.WriteLine("\n登录成功\n" + "这是e.Url:" + e.Url + "\n这是webBrowser1.Document.Url:" + webBrowser1.Document.Url);
                    webBrowser1.Navigate(BaiduThirdUrl);
                }
                else if (e.Url.LocalPath == "/i/app/open_share_api" && !isPosted)
                {
                    Debug.WriteLine("\n准备发帖\n" + "这是e.Url:" + e.Url + "\n这是webBrowser1.Document.Url:" + webBrowser1.Document.Url);
                    Random rnd = new Random();
                    postBaiduTieba(baiduCommentList[rnd.Next(baiduCommentList.Count)]);
                    isPosted = true;
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(1000);
                }
            }
            //             if (e.Url.ToString().IndexOf("javascript:''") > 0)
            //             {
            //                 Debug.WriteLine("\n发帖成功\n" + "这是e.Url:" + e.Url + "\n这是webBrowser1.Document.Url:" + webBrowser1.Document.Url);
            //                 webBrowser1.Navigate(baiduLoginUrl);
            //             }

        }

        //         void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        //         {
        //             if (isInterrupt)
        //             {
        //                 isInterrupt = false;
        //                 return;
        //             }
        //             ((WebBrowser)sender).Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);
        // 
        // 
        //             //throw new NotImplementedException();
        //             if (e.Url.ToString()==baiduLoginUrl)
        //             {
        //                 if ((baiduUserCount) >= baiduUserList.Count)
        //                 {
        //                     baiduUserCount = 0; //用户从头再来
        //                 }
        // 
        //                 if (loginBaidu(baiduUserList[baiduUserCount], baiduPasswordList[baiduUserCount]))
        //                 {
        //                     richTextBox2.AppendText(baiduUserList[baiduUserCount] + " 登录百度成功。");
        // 
        //                     webBrowser1.Navigate(BaiduThirdUrl);
        //                     Application.DoEvents();
        //                     baiduUserCount++;
        //                 }
        //                 else
        //                 {
        //                     richTextBox2.AppendText(baiduUserList[baiduUserCount] + " 登录百度失败。");
        //                     webBrowser1.Navigate(baiduLoginUrl);    //登录下一个用户
        //                 }
        //             }
        //             else if (e.Url.ToString().IndexOf("/i/app/open_share_api")>0)
        //             {
        //                 postBaiduTieba("这个游戏不错，很給力!");
        //                 Application.DoEvents();
        //                 System.Threading.Thread.Sleep(1000);
        //             }
        //         }
        // 
        private void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            // Ignore the error and suppress the error dialog box. 
            e.Handled = true;
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileName != null)
            {
                baiduUserList.Clear();
                baiduPasswordList.Clear();
                textBox1.Text = openFileDialog1.FileName;

                string[] tmpFile = System.IO.File.ReadAllLines(openFileDialog1.FileName);
                foreach (string s in tmpFile)
                {
                    string[] split = s.Trim().Split(':');
                    baiduUserList.Add(split[0]);
                    baiduPasswordList.Add(split[1]);
                }
            }

        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileName != null)
            {
                baiduCommentList.Clear();
                toolStripButton1.Enabled = true;
                toolStripButton2.Enabled = true;
                toolStripButton5.Enabled = true;
                textBox2.Text = openFileDialog1.FileName;

                string[] tmpFile = System.IO.File.ReadAllLines(openFileDialog1.FileName,Encoding.Default);
                foreach (string s in tmpFile)
                {
                    baiduCommentList.Add(s);
                }
            }
        }

    }
}
